package org.example;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MappingRuleDAO {
    private Connection connection;
    private ObjectMapper objectMapper = new ObjectMapper();

    public MappingRuleDAO(Connection connection) {
        this.connection = connection;
    }

    public void createTable() throws SQLException {
        String sql = "CREATE TABLE IF NOT EXISTS mapping_rules (" +
                "id BIGINT PRIMARY KEY AUTO_INCREMENT, " +
                "source_field VARCHAR(255), " +
                "target_field VARCHAR(255), " +
                "target_table varchar(255) null," +
                "conversion_type VARCHAR(50), " +
                "enum_mapping TEXT, " +
                "date_format VARCHAR(50), " +
                "foreign_key_table VARCHAR(255), " +
                "foreign_key_column VARCHAR(255)," +
                "foreign_key_target_column varchar(255) null," +
                "file_path varchar(255) null," +
                "default_value VARCHAR(255) null);";
        try (Statement stmt = connection.createStatement()) {
            stmt.executeUpdate(sql);
        }
    }

    public void saveRule(MappingRule rule) throws SQLException {
        String sql = "INSERT INTO mapping_rules (source_field, target_field, conversion_type, " +
                "enum_mapping, date_format, foreign_key_table, foreign_key_column, target_table, foreign_key_target_column, file_path, default_value) VALUES " +
                "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, rule.getSourceField());
            pstmt.setString(2, rule.getTargetField());
            pstmt.setString(3, rule.getConversionType());

//            String enumJson = "{}";
//            try {
//                if (rule.getEnumMapping() != null && !rule.getEnumMapping().isEmpty()) {
//                    enumJson = objectMapper.writeValueAsString(rule.getEnumMapping());
//                }
//            } catch (JsonProcessingException e) {
//                e.printStackTrace();
//            }
            pstmt.setString(4, rule.getEnumMapping());

            pstmt.setString(5, rule.getDateFormat());
            pstmt.setString(6, rule.getForeignKeyTable());
            pstmt.setString(7, rule.getForeignKeyColumn());
            pstmt.setString(8, rule.getTargetTable());
            pstmt.setString(9, rule.getForeignKeyTargetColumn());
            pstmt.setString(10, rule.getFilePath());
            pstmt.setString(11, rule.getDefaultValue());

            pstmt.executeUpdate();
        }
    }

    public List<MappingRule> getAllRules() throws SQLException {
        List<MappingRule> rules = new ArrayList<>();
        String sql = "SELECT * FROM mapping_rules";
        try (Statement stmt = connection.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {

            while (rs.next()) {
                MappingRule rule = new MappingRule();
                rule.setSourceField(rs.getString("source_field"));
                rule.setTargetField(rs.getString("target_field"));
                rule.setConversionType(rs.getString("conversion_type"));

                try {
                    String enumJson = rs.getString("enum_mapping");
                    if (enumJson != null && !enumJson.isEmpty()) {
                        @SuppressWarnings("unchecked")
                        Map<String, String> enumMap = objectMapper.readValue(enumJson, HashMap.class);
                        rule.setEnumMapping(enumMap.toString());
                    }
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }

                rule.setDateFormat(rs.getString("date_format"));
                rule.setForeignKeyTable(rs.getString("foreign_key_table"));
                rule.setForeignKeyColumn(rs.getString("foreign_key_column"));
                rule.setFilePath(rs.getString("file_path"));

                rules.add(rule);
            }
        }
        return rules;
    }


    public void deleteRulesByName(String targetTableName) throws SQLException {
        String sql = "DELETE FROM mapping_rules where target_table =" + "'" + targetTableName + "'";
        try (Statement stmt = connection.createStatement()) {
            stmt.executeUpdate(sql);
        }
    }





}